package main

import (
	"net/http"
	"core"
	"encoding/json"
	"io"
	"os/exec"
	"log"
	"time"
)


var blockchain *core.Blockchain

func run(){
	http.HandleFunc("/blockchain/get",blockchainGetHandler)

	http.HandleFunc("/blockchain/write",blockchainWriteHandler)


	http.HandleFunc("/ops",ops)

	http.ListenAndServe(":8888",nil)
}


func blockchainGetHandler(w http.ResponseWriter,r *http.Request){
	bytes,error:=json.Marshal(blockchain)
	if error!=nil{
		http.Error(w,error.Error(),http.StatusInsufficientStorage)
	}
	io.WriteString(w,string(bytes))
}

func blockchainWriteHandler(w http.ResponseWriter,r *http.Request){
	blockData:=r.URL.Query().Get("data")
	blockchain.SendData(blockData)
	blockchainGetHandler(w,r)
}



func ops(w http.ResponseWriter,r *http.Request){
	io.WriteString(w,"<h1>ops!</h1>")
	time.Sleep(5*time.Millisecond)
	reLaunch()
}

func reLaunch(){
	cmd:=exec.Command("sh","./ops.sh")
	err:=cmd.Start()
	if err!=nil{
		log.Fatal(err)
	}
	err=cmd.Wait()
}

func main() {
	blockchain=core.NewBlockchain()
	run()
}